<template>
  <div class="">
    <ProTable
        ref="proTableRef"
        :tableSource="tableData"
        :columns="columns"
        @onload="getList"
        @add="table_add"
        :initParam="{}"
    >

      <template #bodyCell="{record,column}">
        <template v-if="column.dataIndex === 'operation'">
          <ProButton type="link"
                     :options="record.code === 'ADMIN' ? ['edit'] : ['edit','delete']"
                     :cancel="tabke_item_cancel"
                     :finished="(status)=>table_item_finished(status,record)"></ProButton>
        </template>
        <template v-else>
          {{ record[column.dataIndex] }}
        </template>
      </template>
    </ProTable>

    <pro-modal v-model="visable" :title="is_add?'新增':'编辑'" is-drawer @close="modal_cancel">
      <ProForm ref="lgformRef" :initParam="{}" :configure="configure"  v-bind="formOptions"></ProForm>
      <a-divider orientation="left" plain>授权信息</a-divider>
      <a-tree
          v-model:checkedKeys="checkedKeys"
          checkable
          :tree-data="treeData"
          :fieldNames="{children:'children', title:'name', key:'id' }"
      >
      </a-tree>

      <template #footer>
        <ProButton type="primary" :options="['submit','close']" :cancel="modal_cancel" :finished="modal_finished"></ProButton>
      </template>
    </pro-modal>



  </div>
</template>

<script setup lang="ts">
import fetchCommonApi from "@/api/common";
import fetchApi from "@/api/system/role";
import { buttonType } from "@/components/ProButton/interface";
import type { FormProps } from "@/components/ProForm";
import ProForm from "@/components/ProForm";
import type { TableProps } from "@/components/ProTable";
import ProTable from "@/components/ProTable";
import { arrayToTree, treeToArray } from "@/utils/utils";
import { getCurrentInstance, nextTick, onMounted, ref, watch } from "vue";

const { proxy }:any = getCurrentInstance();

onMounted(()=>{
  getMenu()
});

const tableData = ref<TableProps['tableSource']>({
  current:1,
  pageSize:20,
  total:0,
  list:[]
})

const visable = ref(false);
const proTableRef = ref();
const lgformRef = ref();
const configure:FormProps['configure']  = [{"type":"text","label":"名称","span":24,"prop":"name","searchInitParam":"","enum":[],"searchProps":{"disabled":false,"readonly":false,"required":true,"max":100},
  "rules":[{"type":"string","required":true,"max":100,"min":1,"message":"请输入1-100个字符","trigger":["change","blur"]}]},
  {"type":"text","label":"编码","span":24,"prop":"code","searchInitParam":"","enum":[],"searchProps":{"disabled":false,"readonly":false,"required":true,"max":100},
    "rules":[{"type":"string","required":true,"max":100,"min":1,"message":"请输入1-100个字符","trigger":["change","blur"]}]},
  {"type":"textarea","label":"描述","span":24,"prop":"remark","searchInitParam":"","enum":[],"searchProps":{"disabled":false,"readonly":false,"required":true,"max":100},
    "rules":[{"type":"string","required":false,"max":100,"min":1,"message":"请输入1-100个字符","trigger":["change","blur"]}]},
  {"type":"number","label":"排序","span":24,"prop":"sort","searchInitParam":0,"enum":[],"searchProps":{"disabled":false,"readonly":false,"required":true,"max":100,"min":0},
    "rules":[{"type":"number","required":true,"max":100,"min":0,"message":"请输入0-100之间数字","trigger":["change","blur"]}]}]
const formOptions = {"showButton":false,"isvalidate":true,"layout":[4,18],"colNum":1};

const treeData = ref<any[]>([]) ;
const edit_info = ref<null|any>(null);
const is_add = ref(true);

const checkedKeys = ref<string[]>([]);

const columns:TableProps['columns'] = [
  {
    title:"角色名",
    dataIndex:"s_name",
    search:true,
    hidden:true
  },
  {
    title:"角色名",
    dataIndex:"name",
  },
  {
    title:"角色编码",
    dataIndex:"code",
  },
  {
    title:"角色描述",
    dataIndex:"remark"
  },
  {
    width:270,
    dataIndex:"operation",
    title:"操作"
  }
]

const getMenu = async ()=>{
   const res = await fetchCommonApi.optionsMenu();
   if(res.code === 200){
     const list = treeToArray(res.data as any,'0');
     treeData.value = arrayToTree(list.map((v)=>({...v,disabled:Boolean(v.disabled)})));
   }
}

const getList = async (params:any)=>{
  const res = await fetchApi.sysRoleList(params)
  if(res.code === 200 && tableData.value ){
    tableData.value.list = res.data.list
    tableData.value.total = res.data.total
    tableData.value.pageSize = params.limit
    tableData.value.current = params.page
  }
}

// 表格行按钮点击事件
const table_item_finished = async (status:buttonType,item:any)=>{
  if(status === 'edit') {
    return await find_menu_info(item)
  }
  if(status === 'delete'){
    return await table_delete(item)
  }
  return Promise.resolve()
}

const find_menu_info = async (item:any)=>{
   const res = await fetchApi.sysFindRole(item.id);
   if(res.code === 200){
     edit_info.value = res.data
     visable.value = true
     await nextTick();
     is_add.value = false
     lgformRef.value.updateFormByKey('name',item.name);
     lgformRef.value.updateFormByKey('code',item.code);
     lgformRef.value.updateFormByKey('remark',item.remark);
     lgformRef.value.updateFormByKey('sort',item.sort);
     checkedKeys.value = res.data.menus.map((v:any)=>v.id)

     console.log(lgformRef.value)
   }
}

// 删除
const table_delete = async (item:any)=>{
  const res = await fetchApi.sysDeleteRole(item.id)
  proxy.$format.response(res)
  proTableRef.value.refresh();
}

const table_add = ()=>{
  visable.value = true
}

const tabke_item_cancel = ()=>{
  alert("取消")
}

const modal_cancel = ()=>{
  visable.value = false
  lgformRef.value.resetForm()
  edit_info.value = null
  is_add.value = true
  checkedKeys.value = []
}

const modal_finished = async (status:buttonType)=> {
  switch (status){
    case "submit":
      return await modal_submit();
  }
}

// 提交
const modal_submit = async ()=>{
  try {
    const data = await lgformRef.value.validate()
    if(!data) return false
    let res;
    let menu_ids = checkedKeys.value.join(',')
    if(is_add.value) res = await fetchApi.sysAddRole({...data,menu_ids});
    if(!is_add.value) res = await fetchApi.sysUpdateRole({...data,id:edit_info.value.id,menu_ids});

    proxy.$format.response(res)
    proTableRef.value.refresh();
    await modal_cancel()

  }catch (e) {
    console.log("提交",e)
  }
}

watch(()=>checkedKeys.value,()=>{
  console.log(checkedKeys.value)
},{
  immediate:true,
  deep:true
})

</script>

<style scoped lang="less">
.ant-drawer-footer .ProButton{
  :deep(.ant-btn){
    margin-right: 10px !important;
  }
}
</style>
